#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time     : 2025/4/25 16:30
# @Author   : MingTai
# @File     : mp4_compression.py
# 视频压缩，只支持MP4
from moviepy.editor import VideoFileClip

from app.utils.time_util.time_handle import get_second_time_str


def compress_mp4(input_path, output_path, target_bitrate="500k", target_size=None):
    """
    压缩 MP4 视频文件。

    :param input_path: 输入视频文件的路径
    :param output_path: 输出视频文件的路径
    :param target_bitrate: 目标比特率，默认为 500k
    :param target_size: 目标文件大小（MB），若指定则根据此调整比特率
    """
    clip = VideoFileClip(input_path)

    if target_size:
        # 计算根据目标大小得出的比特率
        duration = clip.duration
        target_bitrate = int((target_size * 8 * 1024 * 1024) / duration)
        target_bitrate = f"{target_bitrate}k"

    # 调整分辨率和比特率
    new_clip = clip.resize(0.6)  # 将分辨率缩小为原来的一半，可根据需求调整
    new_clip.write_videofile(output_path, bitrate=target_bitrate)

    clip.close()
    new_clip.close()


if __name__ == "__main__":
    input_file = "video_color_20250424233438.mp4"  # 替换为实际的输入视频文件路径
    output_file = f"compress_{get_second_time_str()}.mp4"  # 替换为实际的输出视频文件路径
    compress_mp4(input_file, output_file)
